<template>
  <div class="flex items-center px-0 select-none">
    <slot></slot>111
    <el-pagination
      v-model:current-page="state.page"
      v-model:page-size="state.limit"
      :total="total"
      :page-sizes="pageSizes"
      :disabled="disabled"
      :background="background"
      :layout="layout"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script setup lang="ts">
import type { TableInstance } from 'element-plus'
import type { Ref } from 'vue'

import { pageSizes } from '@/config'

interface IEmit {
  (event: 'change'): void
  (event: 'update:page', value: number): void
  (event: 'update:limit', value: number): void
}

interface IProps {
  page: number
  limit: number
  total: number
  border?: boolean
  disabled?: boolean
  background?: boolean
  layout?: string
  tableRef?: Ref<TableInstance>
}

const emit = defineEmits<IEmit>()
const props = withDefaults(defineProps<IProps>(), {
  border: false,
  disabled: false,
  background: false,
  layout: 'total,sizes,prev,pager,next,jumper'
})

const state = reactive({
  page: 1,
  limit: 10
})

watchEffect(() => {
  state.page = props.page
  state.limit = props.limit
})

/**
 * 分页数据改变（page，limit发生变化都会出发），如果有table实例，则重置表格滚动高度
 */
function handleChange() {
  emit('change')
  if (props.tableRef) {
    props.tableRef.value.setScrollTop(0)
  }
}

/**
 * 处理页码改变
 */
function handlePageChange(val: number) {
  emit('update:page', val)
  handleChange()
}

/**
 * 处理分页大小改变
 */
function handleSizeChange(val: number) {
  state.page = 1
  emit('update:page', state.page)
  emit('update:limit', val)
  handleChange()
}
</script>

<style scoped lang="scss">
:deep(.el-pagination) {
  @apply w-full justify-end;

  .el-pagination__sizes {
    @apply mx-[16px];

    .el-input__wrapper {
      width: 100px;
    }
  }

  .btn-prev,
  .btn-next,
  .el-pager li {
    border: 1px solid rgba(219, 221, 226, 1);
    margin: 0 3px;
    border-radius: 4px;

    // transition: all 0.2s ease-out;
    &.is-active,
    &:hover {
      border-color: rgba(22, 76, 255, 1);
    }
  }

  .btn-prev,
  .btn-next {
    &[disabled] {
      &:hover {
        border-color: #ddd;
      }
    }
  }
}
</style>
